package com.jch.dm.chapter_18_memento.game;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

/**
 * @author: Administrator
 * @create: 2020/04/09 16:02
 **/
public class Gamer {

    /**
     * 所持金钱
     */
    private int money;
    /**
     * 获得的水果
     */
    private List fruits = new ArrayList();
    /**
     * 随机数生成器
     */
    private Random random = new Random();
    /**
     * 表示水果种类的数组
     */
    private static String[] fruitsname= {"苹果","葡萄","香蕉","橘子"};

    public Gamer(int money) {
        this.money = money;
    }
    public int getMoney(){
        return money;
    }
    /**
     * 投掷骰子进行游戏
     */
    public void bet(){
        //掷骰子
        int dice = random.nextInt(6)+1;
        if (dice == 1){
            money += 100;
            System.out.println("所持金钱增加了。");
        }else if (dice == 2) {
            money /= 2;
            System.out.println("所持金钱减半了。");
        }else if (dice == 6) {
            String f = getFruit();
            System.out.println("获得了水果（"+f+"）。");
            fruits.add(f);
        }else {
            System.out.println("什么都没有发生。");
        }
    }

    /**
     * 拍摄快照
     */
    public Memento createMemento(){
        Memento m = new Memento(money);
        Iterator it = fruits.iterator();
        while(it.hasNext()){
            String f = (String) it.next();
            if (f.startsWith("好吃的")){
                m.addFruit(f);
            }
        }
        return m;
    }

    /**
     * 撤销
     * @param memento 状态信息
     */
    public void restoreMemento(Memento memento){
        this.money = memento.money;
        this.fruits = memento.getFruits();
    }

    /**
     * 用字符串表示主人工状态
     * @return 字符串信息
     */
    @Override
    public String toString() {
        return "[money=" + money + ", fruits=" + fruits +", random=" + random +']';
    }

    /**
     * 获得一个水果
     * @return 水果
     */
    private String getFruit() {
        String prefix = "";
        if (random.nextBoolean()){
            prefix = "好吃的";
        }
        return prefix + fruitsname[random.nextInt(fruitsname.length)];
    }
}
